<?php
allowCors();
$company = [];
$company["name"] = CONFIG["company"];
$departments_result = $db->list(["class"=>"Department"],1,CONFIG['database']['max_count']);
$company["departments"]=[];
foreach ($departments_result["list"] as $dept){
    $dept = (array)$dept;
    unset($dept["deptInfo"]);
    unset($dept["deptManagerId"]);
    $group_result = $db->list(["class"=>"Group"],1,CONFIG['database']['max_count'],["dept_id"=>$dept["deptId"]]);

    $dept["groups"]=[];
    foreach ($group_result["list"] as $gp){
        $gp=(array)$gp;
        $gp["members"]=[];
        unset($gp["deptId"]);
        unset($gp['grouperId']);
        if(isset($_REQUEST['show_member'])&&$_REQUEST['show_member']==1){
            $member_result = $db->list(["class" => "User"], 1, CONFIG['database']['max_count'],["gp_id"=>$gp["gpId"],"dept_id"=>$dept["deptId"]]);
            $gp["members"] = $member_result["list"];
        }
        array_push($dept["groups"],$gp);
    }
    array_push($company["departments"],$dept);
}
echo json_encode($company);
